package com.example.config.datasource;

import com.example.config.datasource.DynamicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author ZHAO Yudong
 * @Date 2021/12/7 17:37
 * @description：多数据源配置
 */
@Configuration
public class MultipleDataSourceConfig {

    @Bean("master")
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource createMasterDataSource(){
        return DataSourceBuilder.create().build()   ;
    }

    @Bean("slave1")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource createSlave1DataSource(){
        return DataSourceBuilder.create().build()   ;
    }

    /**
     * 设置动态数据源，通过@Primary 来确定主DataSource
     * @return
     */
    @Bean
    @Primary
    public DataSource createDynamicDataSource(@Qualifier("master") DataSource master, @Qualifier("slave1") DataSource slave1){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        //设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(master);
        //配置多数据源
        Map<Object, Object> map = new HashMap<>();
        map.put("master",master);
        map.put("slave1",slave1);
        dynamicDataSource.setTargetDataSources(map);
        return  dynamicDataSource;
    }

    //原文链接：https://blog.csdn.net/Honnyee/article/details/97936936
}
